package com.zr.rocketmq.producer;

import com.zr.rocketmq.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Component
public class OrderMessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 普通消息发送
    public void sendOrderMessage() {
        // 创建订单
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId("USER_" + System.currentTimeMillis() % 1000);
        order.setProductId("PROD_" + System.currentTimeMillis() % 100);
        order.setQuantity(1);
        order.setAmount(new BigDecimal("99.99"));
        order.setCreateTime(new Date());
        order.setStatus("PENDING");

        // 构建消息
        Message<Order> message = MessageBuilder.withPayload(order).build();
        
        // 发送消息：topic为"order_topic"，tag为"create"
        rocketMQTemplate.syncSend("order_topic:create", message);
        log.info("普通订单消息发送成功，订单ID: {}", order.getOrderId());
    }

    // 发送延迟消息
    public void sendDelayOrderMessage() {
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId("USER_" + System.currentTimeMillis() % 1000);
        order.setProductId("PROD_" + System.currentTimeMillis() % 100);
        order.setQuantity(2);
        order.setAmount(new BigDecimal("199.98"));
        order.setCreateTime(new Date());
        order.setStatus("PENDING");

        Message<Order> message = MessageBuilder.withPayload(order).build();
        
        // 发送延迟消息，延迟级别为3（10秒）
        // 延迟级别：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        rocketMQTemplate.syncSend("order_topic:delay", message, 3000, 3);
        log.info("延迟订单消息发送成功，订单ID: {}", order.getOrderId());
    }
}
